package com.woniuxy.bookmall.intercepters;

import com.sun.org.apache.bcel.internal.generic.FRETURN;
import io.lettuce.core.dynamic.annotation.CommandNaming;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class PermissionIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        log.info("当前请求的路径是:{}",path);

        //获取 session作用域中用户信息  用于判断当前请求 是否登录
        Object userInfo = request.getSession().getAttribute("userInfo");

        //获取请求类型  异步  、同步
        String header = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(header)) {
            //异步请求
            if (userInfo != null) {
                return true ;
            }else {
                //没有登录
                response.getWriter().print("noLogin");
                return false ;
            }
        }else {
            //同步请求
            if (userInfo != null) {
                return true ;
            }else {
                //没有等路
                request.setAttribute("errorInfo","请先登录!");
                request.getRequestDispatcher("/login.html").forward(request,response);
                return false ;
            }
        }
    }
}
